﻿using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Threading;
using System.Xml;
using System.Windows.Forms;

namespace PublicTransport
{
    class GpsMapImageBing : GpsMapImage
    {
        private string imageRequest;

        public GpsMapImageBing(GpsPoint source, GpsPoint destination, int sizeX, int sizeY)
        {
            try
            {
                this.sizeY = sizeY;
                this.sizeX = sizeX;

                zoom = (int)(Math.Log(Math.Min(((double)sizeX) / Math.Abs(source.X - destination.X), ((double)sizeY) / Math.Abs(source.Y - destination.Y)) * 1.46025) / Math.Log(2)) - 1;
                centerPoint = source.getCenterGpsPoint(destination);
                imageRequest = "/Routes?mapSize=" + sizeX + "," + sizeY + "&key=AowOsgRGaqO3ZXL9XkDBxBElvcE9jP_uHuKjyPzSceIOK3dt4hpyHO44ORUNcKc7&wp.0=" + source.getCoordinates() + "&wp.1=" + destination.getCoordinates() + "&travelMode=Walking";
                constructorFinished = true;
                getImage();
            }
            catch (Exception ex)
            {
                error = ex.Message;
                finished = true;
            }
        }

        public override void getImage()
        {
            if (!httpBlock && constructorFinished)
            {
                httpBlock = true;
                finished = false;
                ok = false;
                ThreadStart thread = () =>
                {
                    try
                    {
                        WebRequest webRequest = WebRequest.Create("http://dev.virtualearth.net/REST/v1/Imagery/Map/" + (mapType == 0 ? "Road/" : "AerialWithLabels/") + centerPoint.getCoordinates() + "/" + zoom + imageRequest);
                        webRequest.Timeout = 10000;
                        image = new System.Drawing.Bitmap(((HttpWebResponse)webRequest.GetResponse()).GetResponseStream());
                        webRequest.Abort();
                        httpBlock = false;
                        Point posun = degreesToPixels(centerPoint);
                        upperLeftPixels = new Point((int)Math.Round(posun.X - (double)sizeX / 2.0), (int)Math.Round(posun.Y - (double)sizeY / 2.0));
                        ok = true;
                    }
                    catch (Exception ex)
                    {
                        httpBlock = false;
                        error = ex.Message;
                    }
                    finished = true;
                };
                thread.Invoke();
            }

        }
    }
}
